package utils;

import contacts.Contact;
import contacts.ContactHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HttpGet {

  private static org.apache.log4j.Logger log = utils.Logger.getInstance(HttpGet.class.getName());

  public static void execute(final String url) {
    new Thread(new Runnable() {
      public void run() {
        HttpParams httpParams = new BasicHttpParams();
        // Waiting to make connection
        HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
        // Socket timeout, waiting for data
        HttpConnectionParams.setSoTimeout(httpParams, 2000);

        HttpClient httpClient = new DefaultHttpClient(httpParams);
        try {
          org.apache.http.client.methods.HttpGet get = new org.apache.http.client.methods.HttpGet(url);
          ResponseHandler<String> responseHandler = new BasicResponseHandler();
          String responseBody = httpClient.execute(get, responseHandler);
          if (responseBody.contains("[")) {
            addMissingContacts(responseBody, url.substring(url.indexOf("extraIp=") + "extraIp=".length(), url.length()));
          }
        } catch (SocketTimeoutException e) {
          log.info("Socket timeout, could not read the data");
        } catch (ConnectTimeoutException e) {
          log.info("Connection timeout " + url);
        } catch (HttpHostConnectException e) {
          log.info("Requested url failed " + url);
        } catch (Exception e) {
          log.error("Found error on sending request " + e.getMessage());
        } finally {
          httpClient.getConnectionManager().shutdown();
        }
      }
    }).start();
  }

  private static void addMissingContacts(String contents, String myIp) {
    ContactHelper contactHelper = new ContactHelper();
    contactHelper.setFilePathAndName("./contacts/" + myIp.replace(":", "_") + ".txt");
    contactHelper.loadContacts();
    ArrayList<Contact> incomingContacts = contactHelper.parseContacts(contents);
    ArrayList<Contact> myContacts = contactHelper.getMyContacts();
    for (Contact incomingContact : incomingContacts) {
      boolean add = true;
      for (Contact contact : myContacts) {
        if (incomingContact.getIPAndPort().equals(contact.getIPAndPort()) || incomingContact.getIPAndPort().equals(myIp)) {
          add = false;
        }
      }
      if (add) {
        myContacts.add(incomingContact);
      }
    }
    contactHelper.myContacts = myContacts;
    contactHelper.saveContacts();

  }

  public static void forwardSendname(ArrayList<Contact> contacts, String name, String ipAndPort, int ttl) {
    for (Contact contact : contacts) {
      if (contact.getIPAndPort().equals(ipAndPort) && contact.getName().equals(name))
        continue;

      utils.HttpGet.execute(
        String.format("http://%s/chat/sendname?%s", contact.getIPAndPort(),
          String.format("name=%s&ip=%s&ttl=%d", name, ipAndPort, ttl)));
    }
  }
}
